package com.hava.contentsale.utils.config;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.servlet.ServletContext;

/**
 * Created by yanfa on 2016/11/17.
 * 动态修改数据库配置文件，但不会自动应用。
 */

@Component
public class DBConfigProperty {

    @Resource
    ServletContext servletContext;

    PropertiesConfiguration propertiesConfiguration;


    @PostConstruct
    public void init(){
        System.out.println("Class DBConfigProperty Method init");
        //get the config workhour.properties path
        String property_path = this.getClass().getResource("/") + "db.properties";
        System.out.println(property_path);

        // Apache commons Configuration
        try {
            propertiesConfiguration = new PropertiesConfiguration(property_path);
            //配置自动保存
            this.propertiesConfiguration.setAutoSave(true);
        } catch (ConfigurationException e) {
            System.out.println("Class DBConfigProperty Method [Exception]:" + e.toString());
        }

    }

    public Object getProperty(String key){
        System.out.println("getProperty " + key.toString());
        return this.propertiesConfiguration.getProperty(key);
    }

    public void setProperty(String key,Object value){
        this.propertiesConfiguration.setProperty(key,value);
    }

    @PreDestroy
    public void destroy() {
        System.out.println("Class DBConfigProperty Method destroy");
    }
}
